package zy.blue7.gui.netty.package1.delimiterbasedframedecoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.util.CharsetUtil;

/**
 * @Author: blue7
 * @Date: 2022/2/25 22:34
 * @Version 1.0
 * @Description
 */
public class Server {

    public static void main(String[] args) throws InterruptedException {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {

                        /**
                         *
                         * DelimiterBasedFrameDecoder  可以自动完成以分隔符做结束标志的消息解码
                         *
                         * StringDecoder的功能更简单，将接收到的对象转换成字符串，然后继续调用后面的handler，LineBaseFrameDecoder+StringDecoder组合就是按行切换的文本解码器，
                         * 它被设计用来支持TCP的粘包和拆包。
                         */
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer("*", CharsetUtil.UTF_8)));
                        /**
                         * 将 bytebuf 转换成 string
                         */
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new TimeServerHandler());
                    }
                })
                .bind(8080).sync();
    }
}
